<script setup name="SysUser">
import { userAdd, userDel, userEdit, userGetList} from "@/api/hrp/user";
import {getCurrentInstance, onMounted, reactive} from "vue";
import {useRoute} from "vue-router";
import UserLoginName from "@/views/hrp/user/resetPwd";

const {proxy} = getCurrentInstance();
const {hrp_user_sex, sys_is} = proxy.useDict('hrp_user_sex', 'sys_is');
const route = useRoute();

onMounted(() => {
  pd.queryParams = {...pd.queryParams, ...route.query};
  getList();
});

const pd = reactive({
  open: false,
  title: "",
  form: {},
  userList: [],
  loading: true,
  showSearch: true,
  total: 0,
  daterangeUpdate_time: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    enableFlag: "0"
  },
  rules: {
    userName: [{
      required: true,
      message: "是否不能为空",
      trigger: "change"
    }]
  }

});

/** 查询合作伙伴列表 */
function getList() {
  pd.loading = true;
  if (null != pd.daterangeUpdate_time && '' != pd.daterangeUpdate_time) {
    pd.queryParams.beginTime = pd.daterangeUpdate_time[0];
    pd.queryParams.endTime = pd.daterangeUpdate_time[1];
  }
  userGetList(pd.queryParams).then(res => {
    pd.userList = res.data;
    pd.total = res.total;
    pd.loading = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  pd.queryParams.beginTime = null;
  pd.queryParams.endTime = null;
  pd.queryParams.userName = null;
  pd.daterangeUpdate_time = [];
  proxy.resetForm("queryRef");
  handleQuery();
}


/** 修改按钮操作 */
function handleDel(id) {
  if (!id) {
    return
  }
  proxy.$modal.confirm('是否确认删除用户编号为:"' + id + '"的数据项？').then(function () {
    return userDel(id);
  }).then(() => {
    proxy.$modal.msgSuccess("删除成功");
    pd.open = false;
    getList()
  }).catch(() => {
  });
}

//============================对话框处理==============


/** 新增按钮操作 */
function handleOpen(user) {
  resetUserForm();
  if (user) {
    pd.form = {...pd.form, ...user};
    pd.title = "修改用户";
  } else {
    pd.title = "新增用户";
  }
  pd.open = true;
}

// 表单重置
function resetUserForm() {
  pd.form = {
    userId: undefined,
    loginName: undefined,
    userName: undefined,
    password: undefined,
    mobile: undefined,
    email: undefined,
    sex: undefined,
    isSys: "1",
    isCustomer: "1",
    isSupplier: "1",
    status: "0",
    remark: undefined
  };
  pd.title = "";
  proxy.resetForm("userRef");
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      if (pd.form.userId) {
        userEdit(pd.form).then(res => {
          proxy.$modal.msgSuccess("修改成功");
          pd.open = false;
          getList()
        });
      } else {
        userAdd(pd.form).then(res => {
          proxy.$modal.msgSuccess("新增成功");
          pd.open = false;
          getList()
        });
      }
    }
  });
}

function reSetLoginName(user) {
  proxy.$refs["reSetLoginNameRef"].edit(user);
  getList();
}

/** 用户删除1  */
function handleUserDel(row) {
  proxy.$modal.confirm('确认要删除用户名"' + row.userName + '",账号"' + row.loginName + '"用户吗?').then(function () {
    let user = {userId: row.userId , status: "2"}
    return userEdit(user);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess(text + "删除成功");
  }).catch(function () {
    row.status = row.status === "0" ? "2" : "0";
  });
}

/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.loginName + '"用户吗?').then(function () {
    let user = {userId: row.userId , status: row.status}
    return userEdit(user);
  }).then(() => {
    // getList();
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0";
  });
}


/** 用户状态修改  */
function handleIsCustomerChange(row) {
  let text = row.isCustomer === "0" ? "是" : "不是";
  proxy.$modal.confirm('确认要修改:"' + text + '""' + row.userName + '"用户吗?').then(function () {
    let user = {userId: row.userId , isCustomer: row.isCustomer}
    return userEdit(user);
  }).then(() => {
    // getList();
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.isCustomer = row.isCustomer === "0" ? "1" : "0";
  });
}

/** 用户状态修改  */
function handleIsSupplierChange(row) {
  let text = row.isSupplier === "0" ? "是" : "不是";
  proxy.$modal.confirm('确认要修改:"' + text + '""' + row.userName + '"用户吗?').then(function () {
    let user = {userId: row.userId , isSupplier: row.isSupplier}
    return userEdit(user);
  }).then(() => {
    // getList();
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.isSupplier = row.isSupplier === "0" ? "1" : "0";
  });
}

</script>

<template>
  <div class="app-container">
    <el-form :model="pd.queryParams" ref="queryRef" :inline="true" v-show="pd.showSearch" label-width="68px">
      <el-form-item label="用户昵称" prop="name">
        <el-input v-model="pd.queryParams.userName" placeholder="请输入搜索用户昵称" @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input v-model="pd.queryParams.mobile" placeholder="请输入搜索用户手机号" @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="更新时间" style="width: 308px">
        <el-date-picker v-model="pd.daterangeUpdate_time" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                        start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Search" @click="handleQuery">搜 索</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="Refresh" @click="resetQuery">重 置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleOpen({})" v-hasPermi="['hrp:user:add']">新 增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" v-hasPermi="['hrp:user:add']">导 入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" v-hasPermi="['hrp:user:export']">导 出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="pd.loading" :data="pd.userList">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="用户编号" align="center" key="userId" prop="userId"/>
      <el-table-column label="登录账号" align="center" key="loginName" prop="loginName" :show-overflow-tooltip="true"/>
      <el-table-column label="用户昵称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-link type="primary" @click="handleOpen(scope.row)" v-hasPermi="['sys:example:edit']">
            {{ scope.row.userName }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" key="sex" prop="sex"/>
      <el-table-column label="手机号码" align="center" key="mobile" prop="mobile" :show-overflow-tooltip="true"/>
      <el-table-column label="状态" align="center" key="status">
        <template #default="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                     @change="handleStatusChange(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="是否客户" align="center" key="isCustomer">
        <template #default="scope">
          <el-switch v-model="scope.row.isCustomer" active-value="0" inactive-value="1"
                     @change="handleIsCustomerChange(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="是否供应商" align="center" key="isSupplier">
        <template #default="scope">
          <el-switch v-model="scope.row.isSupplier" active-value="0" inactive-value="1"
                     @change="handleIsSupplierChange(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="是否系统账户" align="center" prop="isSys">
        <template #default="scope">
          <dict-tag :options="sys_is" :value="scope.row.isSys"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updateBy"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="220">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="scope.row.userId !== 1" link type="primary" icon="Edit" @click="handleOpen(scope.row)"
                     v-hasPermi="['sys:example:edit']"> 修改 </el-button>
          <el-button v-if="scope.row.userId !== 1" link type="primary" icon="Delete" @click="handleUserDel(scope.row)"
                     v-hasPermi="['sys:example:edit']"> 删除 </el-button>
          <el-button v-if="scope.row.userId !== 1" link type="primary" icon="Key" @click="reSetLoginName(scope.row)"
                     v-hasPermi="['sys:example:edit']"> 系统账户设置 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="pd.total > 0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                v-model:limit="pd.queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="pd.title" v-model="pd.open" width="700px" append-to-body>
      <el-form ref="userRef" :model="pd.form" :rules="pd.rules" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="名称" prop="userName">
              <el-input v-model="pd.form.userName" placeholder="请输入名称"/>
            </el-form-item>
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="pd.form.mobile" placeholder="请输入手机号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="sex">
              <DictSelect dict="hrp_user_sex" v-model:code="pd.form.sex" @ok=""/>
            </el-form-item>
            <el-form-item prop="isSupplier">
                        <span>
                           <el-tooltip content="是否供应商！" placement="top">
                              <el-icon><question-filled/></el-icon>
                           </el-tooltip>供应商
                        </span>
              <el-switch v-model="pd.form.isSupplier" active-value="0" inactive-value="1"/>
            </el-form-item>
            <el-form-item v-if="!pd.form.userId && pd.form.isSys == 0" label="用户密码" prop="password">
              <el-input v-model="pd.form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="pd.form.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
            <el-form-item label="是否客户" prop="isCustomer">
              <el-switch v-model="pd.form.isCustomer" active-value="0" inactive-value="1"/>
            </el-form-item>
            <!--            <el-form-item label="岗位">-->
            <!--              <el-select v-model="pd.form.postIds" multiple placeholder="请选择">-->
            <!--                <el-option v-for="item in pd.postList" :key="item.postId" :label="item.postName"-->
            <!--                           :value="item.postId" :disabled="item.status == 1"></el-option>-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="pd.form.id" type="primary" @click="submitForm">新 增</el-button>
          <el-button v-if="!pd.form.id" type="success" @click="submitForm">修 改</el-button>
          <el-button v-if="!pd.form.id" type="danger" @click="del(pd.form.id)">删 除</el-button>
          <el-button type="info" @click="pd.open = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <UserLoginName ref="reSetLoginNameRef"/>
  </div>
</template>

<style lang='scss' scoped>

</style>